package com.example.springboot.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.springboot.common.AliPayConfig;
import com.example.springboot.common.AuthAccess;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.entity.Enroll;
import com.example.springboot.entity.News;
import com.example.springboot.entity.Pay;
import com.example.springboot.service.EnrollService;
import com.example.springboot.service.NewsService;
import com.example.springboot.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能：沙箱支付
 * 作者：刘涵茹
 * 日期：2024/3/30 17:29
 */


@RestController
@RequestMapping("/alipay")
public class AliPayController {
    @Autowired
    EnrollService enrollService;
    @Autowired
    NewsService newsService;
    @Autowired
    PayService payService;
    @Resource
    AliPayConfig aliPayConfig;

    private final String CHARSET = "UTF-8";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";

    @AuthAccess
    @GetMapping("/pay")
    public void pay(Integer id, HttpServletResponse httpResponse) throws IOException {
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        //根据订单编号,查询订单相关信息
        Enroll enroll = enrollService.getById(id);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no =  id.toString();
        //付款金额，必填
        News news = newsService.getById(enroll.getNewsid());
        String total_amount = news.getMoney();
        //订单名称，必填
        String subject = enroll.getTitle();

        request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //支付完成后自动跳转页面
        // request.setReturnUrl("")
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @AuthAccess
    @PostMapping("/notify")
    public void payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=================================支付宝异步回调=====================================");
            // 获取支付宝GET过来反馈信息
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String payNo = params.get("trade_no");

            String sign = params.get("sign");
            System.out.println(params);//查看参数都有哪些
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8"); // 调用SDK验证签名
            if(checkSignature){
                //验签通过
                System.out.println("交易名称：" + params.get("subject"));
                System.out.println("交易状态：" + params.get("trade_status"));
                System.out.println("支付宝交易凭证号：" + params.get("trade_no"));
                System.out.println("商户订单号：" + params.get("out_trade_no"));
                System.out.println("交易金额：" + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id：" + params.get("buyer_id"));
                System.out.println("买家付款时间：" + params.get("gmt_payment"));
                System.out.println("买家付款金额：" + params.get("buyer_pay_amount"));

                //更新已支付
                Enroll enroll = enrollService.getById(tradeNo);
                News news = newsService.getById(enroll.getNewsid());
                enroll.setPayfor("已支付");
                enrollService.updateById(enroll);
                //添加支付信息
                Pay pay = new Pay();
                pay.setName(enroll.getTitle());
                pay.setPayNo(payNo);
                pay.setMoney(news.getMoney());
                pay.setBuyerId(enroll.getPartid());
                pay.setPayTime(gmtPayment);
                payService.save(pay);
            }
        }
    }
}
